package musicstore.biz.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import musicstore.biz.AlbumBiz;
import musicstore.biz.ShoppingCartBiz;
import musicstore.entity.Album;
import musicstore.entity.CartItem;
import musicstore.entity.ShoppingCart;

@Service
public class ShoppingCartBizImpl implements ShoppingCartBiz{
	
	@Autowired
	private AlbumBiz albumBiz;
	@Override
	public void addItemToCart(ShoppingCart cart, int albumId) {
		CartItem item = findItem(cart,albumId);
		if(item!=null){
			item.setQty(item.getQty()+1);
		}else{
			Album a = albumBiz.fetchById(albumId);
			item = new CartItem(albumId,a.getTitle(),a.getPrice(),1);
			cart.getItems().add(item);
		}
		
	}

	private CartItem findItem(ShoppingCart cart, int albumId) {
		for(CartItem c : cart.getItems()){
			if(c.getAlbumId()==albumId){
				return c;
			}
		}
		return null;
	}

	@Override
	public void removeItemToCart(ShoppingCart cart, int albumId) {
		CartItem item = findItem(cart,albumId);
		if(item!=null){
			cart.getItems().remove(item);
		}
		
	}

}
